import 'dart:async';
import 'dart:io';
import 'dart:ui';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:ky_tool_plugin/config/ky_project_configure.dart';
import 'package:ky_tool_plugin/http/dio_utils.dart';
import 'package:ky_tool_plugin/http/http_utils.dart';
import 'package:ky_tool_plugin/tools/ky_log_utils.dart';
import 'package:ky_tool_plugin/tools/ky_toast.dart';
import 'package:package_info/package_info.dart';
import 'package:r_upgrade/r_upgrade.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:ky_tool_plugin/sizefit/ky_int_extension.dart';
import 'package:ky_tool_plugin/sizefit/ky_double_extension.dart';


class KYVersionUpdateManager {


  static Future<String> getNewerVersionAndIsForceUpdate({required bool isShowTip,required BuildContext showContext,required String requestUrl,required Color buttonColor}) async{

    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    String currentVersion = packageInfo.version;

    bool isAndroid = false;

    if (Platform.isAndroid){
      // print('run android');
      isAndroid = true;
    }




    String newVersion = '';
    bool isForceUpdate = false;
    String andriodDownloadUrl = 'https://www.pgyer.com/qOmV';
    String iosDownloadUrl = 'https://www.pgyer.com/WThF';



   await HttpUtils.request(Method.GET, requestUrl, {}, success: (result){
      LogUtils.d('getNewVersionAndIsForceUpdate====$result');
      if (result['code'] == 0){
        if (result['data'] is Map){
          Map dataMap = result['data'];
          String versionKey;
          if (isAndroid){
            versionKey = 'version';
            if (dataMap.keys.contains('andriod_download')){
              if (dataMap['andriod_download'] is String){
                andriodDownloadUrl = dataMap['andriod_download'];
              }
            }
          }else{
            versionKey = 'ios_version';
            if (dataMap.keys.contains('ios_download')){
              if (dataMap['ios_download'] is String){
                iosDownloadUrl = dataMap['ios_download'];
              }
            }
          }
          if (dataMap.keys.contains(versionKey)){
            if (dataMap[versionKey] is String){
              String versionStr = dataMap[versionKey];
              newVersion = versionStr.replaceAll('v', '').replaceAll('V', '');
            }
          }
          if (dataMap.keys.contains('forced_update')){
            if (dataMap['forced_update'] is String){
              if (int.parse(dataMap['forced_update']) == 1){
                isForceUpdate = true;
              }else{
                isForceUpdate = false;
              }
            }
            if (dataMap['forced_update'] is int){
              if (dataMap['forced_update'] == 1){
                isForceUpdate = true;
              }else{
                isForceUpdate = false;
              }
            }
          }
        }
      }

//      currentVersion = '1.0.0';
//      newVersion = '1.0.1';

      LogUtils.d('isForce====$isForceUpdate===oldVersion$currentVersion===newVersion====$newVersion');

      List currentArr = currentVersion.split('.');
      List appStoreArr = newVersion.split('.');

      bool isShow = false;
      bool isSH = false;
      if (currentArr.length == appStoreArr.length){
        if (int.parse(currentVersion.replaceAll('.', '')) < int.parse(newVersion.replaceAll('.', ''))){
          isShow = true;
        }

        if (int.parse(currentVersion.replaceAll('.', '')) > int.parse(newVersion.replaceAll('.', ''))){
          isSH = true;
        }else{
          isSH = false;
        }

      }else{

        if (currentArr.length <= 3 && appStoreArr.length <= 3){

          if (int.parse(currentArr[0]) < int.parse(appStoreArr[0])){
            isShow = true;
          }else if (int.parse(currentArr[0]) == int.parse(appStoreArr[0])){
            if (int.parse(currentArr[1]) < int.parse(appStoreArr[1])){
              isShow = true;
            }
          }
          if (int.parse(currentArr[0]) > int.parse(appStoreArr[0])){
            isSH = true;
          }else if (int.parse(currentArr[0]) == int.parse(appStoreArr[0])){
            if (int.parse(currentArr[1]) > int.parse(appStoreArr[1])){
              isSH = true;
            }else{
              isSH = false;
            }
          }else{
            isSH = false;
          }

        }else {
          if (int.parse(currentVersion.replaceAll('.', '')) < int.parse(newVersion.replaceAll('.', ''))){
            isShow = true;
          }
          if (int.parse(currentVersion.replaceAll('.', '')) > int.parse(newVersion.replaceAll('.', ''))){
            isSH = true;
          }else{
            isSH = false;
          }
        }

      }
      if (isShowTip == true){
        if (isShow == false){
//          KYToast.showText('当前已是最新版本～');
        }else{

          if (isAndroid){


            showDialog<Null>(
                context: showContext,
                barrierDismissible: false,
                builder: (BuildContext context1){
                  return WillPopScope(
                    onWillPop: () async => false,
                    child: KYUpdatePageDialog(
                      contentStr: '当前有新版本，是否更新',
                      backMiss: false,
                      buttonTitlesColorsList: [KYTextBlackColor,KYNavOrangeColor],
                      buttonTitlesList: ['取消','更新'],
                      buttonClickCallBack: (value) async{
                        if (value == 0){
                          LogUtils.d('取消');
                          if (isForceUpdate == false){
                            Navigator.pop(context1);
                          } else {
                            KYToast.showText('该版本比较重要，建议更新哦～');
                          }
                        }
                        if (value == 1){

                          int id = (await RUpgrade.upgrade(
                              'http://static.download.idol001.com/android/apk/idol_v7.6.4_250_2021_03_19_S007.apk',
                              fileName: '客服系统.apk',isAutoRequestInstall: false))!;

                        }
                      },
                    ),
                  );

                });

            // showDialog(
            //     barrierDismissible: false,//点击灰色背景的时候是否消失弹出框
            //     context: showContext,
            //     builder: (context1) {
            //       return new WillPopScope(
            //         onWillPop: () async => false,
            //         child: AlertDialog(
            //           title: Text("温馨提示"),
            //           content: Text("当前有新版本，是否前往更新"),
            //           actions: <Widget>[
            //
            //             TextButton(
            //
            //               child: Text("取消",style: TextStyle(color: buttonColor),),
            //               onPressed: () {
            //                 if (isForceUpdate == false){
            //                   Navigator.pop(context1);
            //                 } else {
            //                   KYToast.showText('该版本比较重要，建议更新哦～');
            //                 }
            //               },
            //             ),
            //             TextButton(
            //
            //               child: Text("复制链接",style: TextStyle(color: buttonColor),),
            //               onPressed: () {
            //                 Clipboard.setData(ClipboardData(text: andriodDownloadUrl));
            //                 KYToast.showText('复制成功');
            //               },
            //             ),
            //             TextButton(
            //               child: Text("更新",style: TextStyle(color: buttonColor),),
            //               onPressed: () async{
            //                 if (isForceUpdate == false){
            //                   Navigator.pop(context1);
            //                 }
            //
            //                 // Dio().download('https://www.pgyer.com/qOmV', 'savePath',onReceiveProgress: (progress, value){
            //                 //
            //                 // },).then((value){
            //                 //
            //                 // });
            //
            //                 int id = (await RUpgrade.upgrade(
            //                     'http://static.download.idol001.com/android/apk/idol_v7.6.4_250_2021_03_19_S007.apk',
            //                     fileName: 'app-release.apk',isAutoRequestInstall: true))!;
            //
            //                 // Clipboard.setData(ClipboardData(text: andriodDownloadUrl));
            //                 // if (await canLaunch(andriodDownloadUrl)) {
            //                 //   await launch(andriodDownloadUrl);
            //                 // } else {
            //                 //   KYToast.showText('下载链接已复制，您也可以手动前往浏览器粘贴下载～');
            //                 //   throw 'Could not launch $andriodDownloadUrl';
            //                 // }
            //
            //               },
            //             )
            //           ],
            //         ),
            //       );
            //     });

          }else{
            showDialog(
                barrierDismissible: false,//点击灰色背景的时候是否消失弹出框
                context: showContext,
                builder: (context1) {
                  return new WillPopScope(
                    onWillPop: () async => false,
                    child: AlertDialog(
                      title: Text("温馨提示"),
                      content: Text("当前有新版本，是否前往更新"),
                      actions: <Widget>[
                        TextButton(

                          child: Text("取消",style: TextStyle(color: buttonColor),),
                          onPressed: () {
                            if (isForceUpdate == false){
                              Navigator.pop(context1);
                            } else {
                              KYToast.showText('该版本比较重要，建议更新哦～');
                            }
                          },
                        ),
                        TextButton(
                          child: Text("更新",style: TextStyle(color: buttonColor),),
                          onPressed: () async{
                            if (isForceUpdate == false){
                              Navigator.pop(context1);
                            }
                            Clipboard.setData(ClipboardData(text: iosDownloadUrl));
                            if (await canLaunch(iosDownloadUrl)) {
                              await launch(iosDownloadUrl);
                            } else {
                              KYToast.showText('下载链接已复制，您也可以手动前往浏览器粘贴下载～');
                              throw 'Could not launch $iosDownloadUrl';
                            }
                          },
                        )
                      ],
                    ),
                  );
                });
          }

        }
      }


      LogUtils.d('isSh====$isSH====isShow====$isShow');


    },fail: (code,msg){
      LogUtils.d('getNewVersionAndIsForceUpdate===$code');
    });


   return '';
  }


}


class KYUpdatePageDialog extends Dialog{

  String contentStr;
  bool backMiss;
  List <String>buttonTitlesList;
  List <Color>buttonTitlesColorsList = [KYTextBlackColor,KYNavOrangeColor];
  //0 1 2 点击返回值
  final buttonClickCallBack;
  KYUpdatePageDialog({required this.contentStr,required this.backMiss,required this.buttonTitlesList,required this.buttonTitlesColorsList,this.buttonClickCallBack});


  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return KYUpdatePage(contentStr: this.contentStr,backMiss: this.backMiss,buttonTitlesColorsList: this.buttonTitlesColorsList,buttonTitlesList: this.buttonTitlesList,buttonClickCallBack: this.buttonClickCallBack,);
  }

}


class KYUpdatePage extends StatefulWidget{
  String contentStr;
  bool backMiss;
  List <String>buttonTitlesList;
  List <Color>buttonTitlesColorsList = [KYTextBlackColor,KYNavOrangeColor];
  //0 1 2 点击返回值
  final buttonClickCallBack;
  KYUpdatePage({required this.contentStr,required this.backMiss,required this.buttonTitlesList,required this.buttonTitlesColorsList,this.buttonClickCallBack});
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return KYUpdatePageState();
  }

}

class KYUpdatePageState extends State<KYUpdatePage>{

  late StreamSubscription upgradeSubscription;
  bool _isAndriodUpdating = false;
  DownloadInfo _downloadInfo = DownloadInfo(
    maxLength: 100,
    currentLength: 0,
    percent: 0,
    status: DownloadStatus.STATUS_PENDING,
  );


  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    upgradeSubscription = RUpgrade.stream.listen((event) {
      LogUtils.d('downLoadProgress==========${event.currentLength}====${event.maxLength}=====${event.status}===${event.percent}');

      if (mounted){
        _downloadInfo = event;
        setState(() {

        });

        if (_downloadInfo.status == DownloadStatus.STATUS_SUCCESSFUL){
          LogUtils.d('下载成功，开始安装======');
          _isAndriodUpdating = false;
          Navigator.of(context).pop();
          RUpgrade.install(event.id!);
        }
      }


    });

  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    upgradeSubscription.cancel();
  }


  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    double buttonWidth = (325-0.5).px/2.0;
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: (){
        // if(widget.backMiss){
        //   Navigator.of(context).pop();
        // }
      },
      child: Material(
        type: MaterialType.transparency,
        child: Center(
          child: Container(
            width: 325.px,
            height: 200.px,
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.all(Radius.circular(4.px)),
            ),
            child: Column(
              children: <Widget>[
                Container(
                  padding: EdgeInsets.only(left: 25.px,right: 25.px),
                  height: 149.5.px,
                  alignment: Alignment.center,
                  child: (_isAndriodUpdating == false)?Text(widget.contentStr,style: TextStyle(fontSize: 15.px),textAlign: TextAlign.center,):Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      LinearProgressIndicator(value: (_downloadInfo.currentLength!)/(_downloadInfo.maxLength!)),
                      SizedBox(height: 8.px,),
                      Text('下载中${_downloadInfo.percent}%...',style: TextStyle(color: KYTextBlackColor,fontSize: 13.px),)
                    ],
                  ),
                ),
                Container(
                  height: 0.5.px,
                  color: Color(0xFFEDEDED),
                ),
                (widget.buttonTitlesList.length == 1)?GestureDetector(
                  onTap: (){
                    if (_isAndriodUpdating == true){
                      return;
                    }
                    widget.buttonClickCallBack(0);
                  },
                  child: Container(
                    height: 50.px,
                    color: Colors.white,
                    alignment: Alignment.center,
                    child: Text(widget.buttonTitlesList[0],style: TextStyle(color: widget.buttonTitlesColorsList[0],fontSize: 15.px),),
                  ),
                ):Container(
                  height: 50.px,
                  child: Row(
                    children: <Widget>[
                      GestureDetector(
                        onTap: (){
                          if (_isAndriodUpdating == true){
                            return;
                          }
                          widget.buttonClickCallBack(0);
                        },
                        child: Container(
                          width: buttonWidth,
                          height: double.infinity,
                          color: Colors.transparent,
                          alignment: Alignment.center,
                          child: Text(widget.buttonTitlesList[0],style: TextStyle(fontSize: 15.px,color: widget.buttonTitlesColorsList[0]),),
                        ),
                      ),
                      Container(width: 0.5.px,color: Color(0xFFEDEDED),),
                      GestureDetector(
                        onTap: (){

                          if (_isAndriodUpdating == true){
                            return;
                          }
                          _isAndriodUpdating = true;
                          if (mounted){
                            setState(() {

                            });
                          }
                          widget.buttonClickCallBack(1);
                        },
                        child: Container(
                          width: buttonWidth,
                          height: double.infinity,
                          color: Colors.transparent,
                          alignment: Alignment.center,
                          child: Text(widget.buttonTitlesList[1],style: TextStyle(fontSize: 15.px,color: widget.buttonTitlesColorsList[1]),),
                        ),
                      )
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

}

